<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\ads\Ad as AdModel;
use app\common\model\ads\Order as AdOrderModel;
use app\common\model\ads\Comment;
use app\common\model\ads\CommentZan;
use app\common\validate\ads\Ad as AdValidate;
use app\common\model\User;
use think\Db;
use think\Config;
use app\common\model\score\Task;
use app\common\model\printmanager\Goods;
use app\common\service\Amount;
use app\common\service\Redpack;
use app\common\library\AddressCode;
use fast\Random;

/**
 * 赏金广告接口
 */
class Ad extends Api
{
    protected $noNeedLogin = ['getAdList', 'getAdInfo', 'adCommentList'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     */
    public function index()
    {
        $this->success('', ['welcome' => '123']);
    }

    /**
     * 获取广告列表
     */
    public function getAdList()
    {
        $where['status'] = 1;   //审核通过
        $where['display'] = 1;  //允许展示
        $is_recommend = input('is_recommend/d', 1); //默认推荐
        
        $area_code = null;

        if ($is_recommend != 1) {
            #同城的
            $area_code = AddressCode::parse( input('area_code/d', 0) ); //区域编码
        }

        // $longitude = input('longitude', -1);    //经度
        // $latitude = input('latitude', -1);  //纬度

        $field = array(
            'id',
            'user_id',
            'title',
            'content',
            'type',
            'category',
            'money_amount',
            'money_count',
            'range',
            'files',
            'effecttime',
            'createtime',
            'toptime',
            'get_num',
            'click_count'
        );

        if($is_recommend==1){
            $adList = AdModel::field($field)
            ->where($where)
            ->where(function($query){
                $query->where('recommendtime','gt', time());
                $query->whereOr('sort', '>', 0);
            })
            ->order('sort DESC, istop DESC, money_amount DESC, createtime DESC')
            // ->fetchSql(1)
            // ->select();
            // var_dump($adList);die;
            ->paginate()
            ->each(function ($item, $key) {
                $item->user_info = $item->user_info;
                $item->favorite_num = $item->favorite_num;
                $item->comment_num = $item->comment_num;
                $item->money_mark = $item->money_mark;
                $item->file_list = $item->file_list;
            });
        }else{
            $model = AdModel::field($field)
            ->where($where);
            if($area_code){
                // 同城的
                if($area_code['county'] > 0){
                    $model = $model->where(function($query) use($area_code){
                        $query->whereOr('county', $area_code['county'])->whereOr(function($query) use($area_code){
                            $query->where('county', 0);
                            $query->where('city', $area_code['city']);
                        })
                        ->whereOr(function($query) use($area_code){
                            $query->where('county', 0);
                            $query->where('city', 0);
                            $query->where('province', $area_code['city']);
                        });
                    });
                }else
                if($area_code['city'] > 0){
                    $model = $model->where(function($query) use($area_code){
                        $query->whereOr('city', $area_code['city'])->whereOr(function($query) use($area_code){
                            $query->where('city', 0);
                            $query->where('province', $area_code['province']);
                        });
                    });
                }else
                if($area_code['province'] > 0){
                    $model = $model->where('province', $area_code['province']);
                }
            }

            $adList = $model->order('sort DESC, istop DESC, money_amount DESC, createtime DESC')
            // ->fetchSql(1)
            // ->select();
            // var_dump($adList);die;
            ->paginate()
            ->each(function ($item, $key) {
                $item->user_info = $item->user_info;
                $item->favorite_num = $item->favorite_num;
                $item->comment_num = $item->comment_num;
                $item->money_mark = $item->money_mark;
                $item->file_list = $item->file_list;
            });
        }

        $this->success('赏金广告', $adList);
    }

    /**
     * 获取广告详情
     * @throws \think\exception\DbException
     */
    public function getAdInfo()
    {
        $id = input('id/d', 0);
        if ($id == 0) {
            $this->error('广告参数有误');
        }
        $where['id'] = $id;
        $where['status'] = 1;   //审核通过
        $where['display'] = 1;  //允许展示

        $adInfo = AdModel::where($where)->find();
        if (!$adInfo) {
            $this->error('广告不存在或已下架');
        }

        $adInfo->setInc('click_count');

        $is_fans = 0;
        $is_self = 0;
        $is_favorute = 0;
        $is_got_gold = 0;

        //是否关注作者
        //是否收藏
        if ($this->auth->isLogin()) {
            $this->ad_history($this->auth->id, $id);
            $where_a['to_user_id'] = $adInfo['user_id'];
            $where_a['user_id'] = $this->auth->id;

            $is_fans = Db::name('self_attention')->where($where_a)->count();

            $where_f['type'] = 0;
            $where_f['data_id'] = $adInfo['id'];
            $where_f['user_id'] = $this->auth->id;
            $is_favorute = Db::name('self_favorite')->where($where_f)->count();
            Task::execute_task(12, $this->auth->id);  // 浏览广告

            $is_self = $adInfo->user_id == $this->auth->id ? 1 : 0;
            $is_got_gold = Redpack::isGotGold($this->auth->id, $adInfo->id);
        }


        $adInfo->user_info = $adInfo->user_info;  //收藏数量
        $adInfo->favorite_num = $adInfo->favorite_num;  //收藏数量
        $adInfo->comment_num = $adInfo->comment_num;  //评论数量
        $adInfo->file_list = $adInfo->file_list;  //文件
        
        $adInfo->is_got_gold = $is_got_gold;
        $adInfo->is_self = $is_self;
        $adInfo->is_fans = $is_fans;
        $adInfo->is_favorute = $is_favorute;
        $adInfo->gold_getters = Redpack::getGotters($adInfo->id, 5, $this->auth->isLogin() ? $this->auth->id : 0);
        $adInfo->money_mark = $adInfo->money_mark;

        // $adInfo = $adInfo->toArray();
        // if(isset($adInfo['category']) && $adInfo['category'] == 1){
        //     #视频类的调整顺序
        //     if(isset($adInfo['file_list'][0]) && isset($adInfo['file_list'][1])){
        //         $adInfo['file_list'] = [$adInfo['file_list'][1], $adInfo['file_list'][0]];
        //     }
        // }
        $this->success('赏金广告', $adInfo);
    }

    /*
     * 广告评论
     */
    public function adCommentList()
    {
        $id = input('id/d', 0);

        $user_id = $this->auth->isLogin() ? $this->auth->id : 0;

        $list = Comment::where('ad_id', $id)->where('pid', 0)->paginate(10)->each(function($item) use($user_id){
            $item->user_info = $item->user_info;
            $item->child_comment = $item->children;
            $item->zan_num = $item->zan_num;
            $item->is_zan = $user_id ? CommentZan::isZan($item->id,$user_id) : 0;
        });

        $this->success('广告评论', $list);
    }

     

    /**
     * 获取发布广告配置信息
     */
    public function getAdConfig()
    {
        $toptime = config('site.toptime');

        $res['toptime'] = [
            'key' => array_keys($toptime),
            'value' => array_values($toptime),
        ];

        $recommendtime = config('site.recommendtime');

        $res['recommendtime'] = [
            'key' => array_keys($recommendtime),
            'value' => array_values($recommendtime),
        ];

        $effecttime = config('site.effecttime');

        $res['effecttime'] = [
            'key' => array_keys($effecttime),
            'value' => array_values($effecttime),
        ];

        $range = config('site.ad_range');

        $res['range'] = [
            'key' => array_keys($range),
            'value' => array_values($range),
        ];

        $res['service_fee'] = config('site.service_fee');

        $this->success('广告参数', $res);
    }
    /**
     * 发布广告
     */
    public function addAd()
    {
        $file_url = input('file_url');
        if(is_string($file_url)) $file_url = explode(",", $file_url);

        $type = input('type/d', 1);
        $user_id = $this->auth->id;

        $data = $this->request->post();
        $rate = config('site.rmb_rate');
        if ($type == 1) {
            // 赏金广告
            (new AdValidate())->goCheck('add_money',  $data);
            $pre = ($data['money_amount'] * $rate) / $data['money_count'];
            if ($pre < 1) {
                $this->error('请确保每份赏金大于1金币');
            }

            #最大份数倍数 100
            $max_bei = 100;
            $max_num = round($data['money_amount'] * $max_bei);
            if($data['money_count'] > $max_num){
                $this->error("最多只能发{$max_num}份赏金");
            }
        } else {
            // 公益广告
            $data['money_amount'] = 0;
            (new AdValidate())->goCheck('add_free', $data);

            #num 
            $max_num_eday = config('site.freead_max_num');
            if($max_num_eday){
                $num = AdModel::where([
                    'user_id' => $user_id,
                    'type' => 2,
                    'createtime' => ['egt', strtotime(date('Y-m-01'))]
                ])->count();
                
                if($num>=$max_num_eday){
                    $this->error("公益广告每月最多发布{$max_num_eday}条");
                }
            }
        }


        $data['user_id'] = $user_id;
        $data['createtime'] = $now_time = time();
        if(isset($data['share_from'])) unset($data['share_from']);
        $effecttime = input('effecttime/d', 0);
        $toptime = input('toptime/d', 0);
        $recommendtime = input('recommendtime/d', 0);
        //有效时间
        if ($effecttime > 0) {
            $data['effecttime'] = $now_time + $effecttime * 24 * 3600;
        }else{
            $data['effecttime'] = 0;
        }

        if ($toptime > 0) {
            $data['toptime'] = $now_time + $toptime * 24 * 3600;
        }else{
            $data['toptime'] = 0;
        }

        //推荐时间
        if ($recommendtime > 0) {
            $data['recommendtime'] = $now_time + $recommendtime * 24 * 3600;
        }else{
            $data['recommendtime'] = 0;
        }

        unset($data['token']);
        unset($data['file_url']);

        Db::startTrans();
        $ad = new AdModel;

        $data['files'] = $file_url ? implode(",", $file_url) : "";
        $in = $ad->allowField(true)->isUpdate(false)->save($data);

        if (!$in) {
            Db::rollback();
            $this->error('数据存储失败');
        }
        $ad_id = $ad['id'];
        
        if ($data['type'] == 1) {
            //红包分配数据
            try {
                $luck_is_success = Redpack::generatorRedpack($ad_id, $ad['money_amount'], $ad['money_count']);
            } catch (\Exception $e) {
                $luck_is_success = false;
                $error = $e->getMessage();
            }
            if (!$luck_is_success) {
                Db::rollback();
                $this->error( isset($error) ? $error : '赏金配置失败');
            }
        }
 
        $ad_order = AdOrderModel::createOrder($ad['id'], $effecttime, $toptime, $recommendtime);

        if (is_null($ad_order)) {
            Db::rollback();
            $this->error('订单生成失败');
        }
        Db::commit();

        if($ad_order === false){
            $this->success('提交成功', [
                'ad_id' => $ad_id
            ]);
        }

        $this->success('提交成功', $ad_order);
    }

    /**
     * 領取賞金
     */
    public function getGold()
    {

        //获取广告信息
        $ad_id = input('ad_id/d', 0);
        if ($ad_id == 0) {
            $this->error('广告参数有误');
        }
        try {
            $res = Redpack::getGold($ad_id, $this->auth->id);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if($res)
        $this->success("{$res}金币已到账");
        else
        $this->error("领取失败");
    }

    /*
     * 评论
     */
    public function adAddComment()
    {
        $data = $this->request->post();
        unset($data['token']);
        //$ad_id = input('ad_id/d', 0);
        //$top_id = input('top_id/d', 0);
        $user_id = $this->auth->getUserinfo()['id'];
        //$data['ad_id'] = $ad_id;
        $data['user_id'] = $user_id;
        //$data['top_id'] = $top_id;
        $data['createtime'] = time();

        if (isset($data['top_id']) && $data['top_id'] !== 0) {
            $pid = Db::name('self_comment')->where(array('id' => $data['top_id']))->value('pid');
            if ($pid && $pid !== 0) {
                $data['pid'] = $pid;
            } else {
                $data['pid'] = $data['top_id'];
            }
        }

        $is_success = Db::name('self_comment')->insertGetId($data);
        if ($is_success) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /*
     * 收藏操作
     */
    public function editFavorite()
    {
        $user_id = $this->auth->getUserinfo()['id'];
        $id = input('id/d', 0);
        $type = input('type/d', 0);

        $data['type'] = $type;
        $data['data_id'] = $id;
        $data['user_id'] = $user_id;
        $fav_info = Db::name('self_favorite')->where($data)->find();
        $is_success = true;
        if ($fav_info) {
            $del = Db::name('self_favorite')->where(array('id' => $fav_info['id']))->delete();
            if ($del === false) {
                $is_success = false;
            }
        } else {
            $data['createtime'] = time();
            $id = Db::name('self_favorite')->insertGetId($data);
            if (!$id) {
                $is_success = false;
            }else{
                Task::execute_task(15, $this->auth->id);
            }
        }

        if ($is_success === false) {
            $this->error('操作失败');
        } else {
            $this->success('操作成功');
        }
    }

    /*
     * 广告点赞
     */
    public function adCommentZan()
    {
        $id = input('id/d', 0);

        $res = CommentZan::zan($id, $this->auth->id);
        if($res)
        $this->success('操作成功', $res);

        $this->error('操作失败');
    }

    /*
     * 我的收藏
     */
    public function FavList()
    {
        $user_id = $this->auth->getUserinfo()['id'];
        $where['user_id'] = $user_id;
        $field = 'id, type, data_id, createtime';
        $fav_list = Db::name('self_favorite')
            ->field($field)
            ->where($where)
            ->order('createtime DESC')
            ->paginate()
            ->each(function($item) {
                $item['createtime_text'] = date('Y-m-d H:i', $item['createtime']);
                if ($item['type'] == 0) {
                    $info = AdModel::where(array('id' => $item['data_id']))->field('id,title,files')->find();
                    $info->file_list =  $info->file_list;
                } else {
                    $info = Goods::where(array('id' => $item['data_id']))->field('id,name as title, price')->find();
                    $info->file_list =  $info->file_list;
                }
                $item['info'] = $info;
                return $item;
            })
            ->toArray();
        $this->success('我的收藏', $fav_list);
    }

    /*
     * 添加看单历史记录
     */
    public function ad_history($user_id, $ad_id)
    {
        $his_info = Db::name('self_history')->where(array('user_id' => $user_id, 'ad_id' => $ad_id))->find();
        if ($his_info) {
            Db::name('self_history')->where(array('id' => $his_info['id']))->update(array('createtime' => time()));
        } else {
            $add_data['user_id'] = $user_id;
            $add_data['ad_id'] = $ad_id;
            $add_data['createtime'] = time();
            Db::name('self_history')->insertGetId($add_data);
        }
    }
    /*
     * 我的发布 广告
     */
    public function MyAd()
    {
        $user_id = $this->auth->getUserinfo()['id'];
        $where['user_id'] = $user_id;
        $field = 'id, title, content, type, files, category, money_amount, money_count, createtime, status, sudit_opinion';
        $order = 'createtime DESC';
        $adList = AdModel::field($field)
            ->where($where)
            ->order($order)
            ->paginate()
            ->each(function($item){
                $item->createtime_text = date('Y-m-d H:i', $item['createtime']);
                $item->order = $item->order;
            })
            ->toArray();
 
        $this->success('我的发布-赏金广告', $adList);
    }

    /*
     * 金币收益明细
     */
    public function goldLog()
    {
       
        $list = \app\common\model\MoneyLog::where([
            'user_id' => $this->auth->id
        ])->order('createtime desc')->paginate();

        $this->success('金币收益明细', $list);
    }
    /*
     * 金币收益
     */
    public function goldData()
    {
        $money = $this->auth->getUserinfo()['money'];
        $user_id = $this->auth->getUserinfo()['id'];
        $rmb_rate = config('site.rmb_rate');
        $money_to_rmb = bcdiv($money, $rmb_rate, 2);
        $today_start = strtotime(date('Y-m-d'));
        $today_end = strtotime(date('Y-m-d') . '+1 day');
        $today_gold = \app\common\model\MoneyLog::where(array('user_id' => $user_id))
            ->where('createtime', ['>=', $today_start], ['<', $today_end], 'and')
            ->sum('money');

        $month_start = strtotime(date('Y-m-01'));
        $month_end =   strtotime(date('Y-m-01')." +1 month -1 day");
        $month_gold = \app\common\model\MoneyLog::where(array('user_id' => $user_id))
        ->where('createtime', ['>=', $month_start], ['<', $month_end], 'and')
        ->sum('money');
        $return_data['money'] = $money;
        $return_data['rmb_rate'] = $rmb_rate;
        $return_data['money_rmb'] = $money_to_rmb;
        $return_data['today_money'] = $today_gold;
        $return_data['month_money'] = $month_gold;
        $return_data['withdraw_limit'] = config('site.withdraw_limit') ? config('site.withdraw_limit') : 10; //提现限制金额
        $this->success('金币收益', $return_data);
    }
}
